<?php
/**
* Projects
* Manage all projects in the system
* 
* @package Project
* @author Argem Gerald R. Flores <argemgrflores@gmail.com>
* @version 1.0
*/
class Project {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = 'proj';
	/**
	* @var string Database table to be used
	*/
	var $table = 'Projects';
	
	/**
	* Project constructor
	* Initializes project variables for intended request
	* 
	* @param string $area Area of concentration
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $mysqli, $user) {
		# Require all necessary classes
		require_once "class/editor.php";
		require_once "class/setting.php";
		require_once "class/fpdf.php";
		require_once "class/file.php";
		require_once "class/resource.php";
		require_once "class/location.php";
		require_once "class/microorganism.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/section.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		# Switch to intended area of concentration
		switch($area) {
			case 'micro':
				$this->table = 'ProjMicros';
			break;
			
			case 'img':
				$this->table = 'ProjImgs';
			break;
			
			case 'doc':
				$this->table = 'ProjDocs';
			break;
		}
	} # function __construct
	
	/**
	* Search project
	* Searches for a project based on
	* query string, optional paramaters as constraints,
	* start and end line of result in a mysql resource
	* 
	* @access public
	* @param string $query Keyword/s to look for in the database
	* @param array $opts Contains constraints in search (category, order, author, etc.)
	* @param integer $start Beginning line of searched keyword in mysql resource
	* @param integer $limit End of returned mysql resource as a result of search
	* 
	* @return array Mixed result from mysql query and size of returned rows
	*/
	public function search($query, $opts, $start, $limit) {
		$query = is_array($query) ? $query : Tool::trimout($query);
		$selSize = "SELECT FOUND_ROWS()";
		
		# Search project via ID
		if($opts["c"]=="id" or $opts["c"]=="view") {
			$query = empty($opts['id']) ? $query : $opts['id'];
			
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Projects AS T1 WHERE T1.ID='{$query}' ".(in_array($this->user['type'], array('ADMIN','PRIME')) ? '' : "AND T1.Remove='0'")."
					AND ('{$this->user['type']}'='PRIME' OR T1.Visib='PUB' OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
					OR (SELECT COUNT(*) FROM ProjCoeds AS T2 WHERE T2.PID='{$query}' AND T2.CID='{$this->user['id']}') > 0)))
				ORDER BY T1.Title
			";
		}
		else {
			$cond = "";
			
			# Switch according to category in constraint list opts
			switch($opts["c"]) {
				# Microorganisms associated with project
				case "micro":
					$categ = "
						INNER JOIN ProjMicros AS T3 INNER JOIN Microorganisms AS T4
							ON T1.ID=T3.PID AND T3.CID=T4.ID
						WHERE T4.ID LIKE '%{$query}%' OR T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
					";
				break;
				
				# Images associated with project
				case "img":
					$categ = "
						INNER JOIN ProjImgs AS T3 INNER JOIN Images AS T4
							ON T1.ID=T3.PID AND T3.CID=T4.ID
						WHERE T4.ID LIKE '%{$query}%' OR T4.Title LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
					";
				break;
				
				# Documents associated with project
				case "doc":
					$categ = "
						INNER JOIN ProjDocs AS T3 INNER JOIN Documents AS T4
							ON T1.ID=T3.PID AND T3.CID=T4.ID
						WHERE T4.ID LIKE '%{$query}%' OR T4.Title LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
					";
				break;
				
				# Locations associated with project
				case "loc":
					$categ = "
						INNER JOIN ProjLocs AS T3 INNER JOIN Locations AS T4
							ON T1.ID=T3.PID AND T3.CID=T4.ID
						WHERE T4.ID LIKE '%{$query}%' OR T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
					";
				break;
				
				# Authors associated with project
				case "edtr":
					if(count($arrQuery = explode(', ', $query)) == 3) {
						$subcond = "(T4.Lname LIKE '%".Tool::trimout($arrQuery[0])."%' AND T4.Fname LIKE '%".Tool::trimout($arrQuery[1])."%') OR T4.Lname LIKE '%{$query}%' OR T4.Fname LIKE '%{$query}%' OR T4.Email LIKE '%{$query}%'";
					}
					else {
						$subcond = "T4.Lname LIKE '%{$query}%' OR T4.Fname LIKE '%{$query}%' OR T4.Email LIKE '%{$query}%'";
					}
					
					$categ = "
						INNER JOIN ProjAuthors AS T3 INNER JOIN Editors AS T4
							ON T1.ID=T3.PID AND T3.CID=T4.ID
						WHERE {$subcond}
					";
				break;
				
				# Multiple ids
				case "multi-id":
					$categ = "WHERE T1.ID IN ('".implode("','", $query)."')";
				break;
				
				# Exact title of project
				case 'exact':
					$cond .= " (T1.Title='{$query}') AND ";
				break;
				
				# Occurrence of title in any part of the string
				case 'title':
					$cond .= " (T1.Title LIKE '%{$query}%') AND ";
				break;
			}
			
			# Order category and ordering
			$opts["ob"] = isset($opts["ob"]) ? $opts['ob'] : "Title";
			$opts["oa"] = isset($opts["oa"]) ? $opts["oa"] : "ASC";
			
			# Include words/phrase
			if(!empty($opts["i"])) {
				$cond .= " (T1.Title LIKE '%{$opts["i"]}%' OR T1.Abstr LIKE '%{$opts["i"]}%' OR T1.Notes LIKE '%{$opts['i']}%') AND ";
			}
			
			# Exclude words/phrase
			if(!empty($opts["e"])) {
				$arrQuery = explode(", ", $opts["e"]);
				$title = "T1.Title NOT LIKE '%".implode("%' OR T1.Title NOT LIKE '%", $arrQuery)."%'";
				$abstr = "T1.Abstr NOT LIKE '%".implode("%' OR T1.Abstr NOT LIKE '%", $arrQuery)."%'";
				$notes = "T1.Notes NOT LIKE '%".implode("%' OR T1.Notes NOT LIKE '%", $arrQuery)."%'";
				$cond .= " ({$title} AND {$abstr} AND {$notes}) AND ";
			}
			
			# Creator
			if(!empty($opts["cb"])) {
				if(empty($opts['cbi'])) {
					$name = explode(", ", $opts["cb"]);
					
					# Last name, First name, Mid name
					if(count($name)==3) {
						list($lname, $fname, $mi) = $name;
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Lname='".Tool::trimout($lname)."'AND Fname='".Tool::trimout($fname)."') AND ";
					}
					# Email
					elseif(strrpos($opts['cb'], '@') > 1) {
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Email='{$opts['cb']}')) AND ";
					}
					# Other
					else {
						$cond .= "(T1.CrtBy='%{$query}%') AND ";
					}
				}
				# Account ID
				else {
					$cond .= " (T1.CrtBy='{$opts['cbi']}') AND ";
				}
			}
			
			# Creation date
			if(!empty($opts["co"]["s"]) and !empty($opts["co"]["e"])) {
				$cond .= " (T1.CrtOn BETWEEN '".Tool::trimout($opts["co"]["s"])."' AND '".Tool::trimout($opts["co"]["e"])."') AND ";
			}
			
			# Removed items
			$cond .= (in_array($this->user['type'], array('ADMIN','PRIME')) and $opts['c']=='remove') ? " T1.Remove='1' AND " : " T1.Remove='0' AND ";
			
			# Limit of returned rows
			$range = (isset($start) and !empty($limit)) ? "LIMIT {$start}, {$limit}" : '';
			
			if(empty($categ)) {
				$cond = "
					WHERE {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ProjCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			else {
				$cond = "
					{$categ} AND {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ProjCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			
			# Final query string
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Projects AS T1 {$cond} ORDER BY T1.{$opts["ob"]} {$opts["oa"]} {$range}
			";
		}
		
		# Search query in datatbase
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results of rows and size of rows
		return array($res, $size[0]);
	} # function search
	
	/**
	* Create project
	* Create a new project entry on the system
	* 
	* @access public
	* @param string $title Title of project 
	* @param string $abstr Abstract
	* @param mixed $authors Authors
	* @param mixed $micros Microorganisms
	* @param mixed $secs Sections
	* @param mixed $secfiles Files in each section
	* @param mixed $srces Sources
	* @param mixed $notes Additional information
	* @param mixed $files Images and documents
	* @param mixed $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	* 
	* @return mixed id on success, false on failure
	*/
	public function create(
		$title, $abstr, $authors, $micros, $secs, $secfiles, $pimg, $pdoc,
		$srces, $notes, $ref, $imgs, $docs, $files, $coeds, $categ, $visib
	) {
		# Generate id for project
		$id = Tool::generateID('proj');
		
		# Insert project string
		$ins = "
			INSERT INTO Projects VALUES (
				'{$id}', '{$categ}', '{$visib}', '".mysql_real_escape_string($title)."', '".mysql_real_escape_string($abstr)."', '".mysql_real_escape_string($notes)."', '".mysql_real_escape_string($ref)."',
				NULL, NULL, '".(empty($coeds["val"]) ? 0 : count($coeds["val"]))."', NULL, NULL, '0', NULL, NULL, '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
			)
		";
		
		# Insert project to database
		if($this->mysqli->query($ins)) {
			# Create and associate primary document entry
			if(!empty($pdoc)) {
				# Instantiate document class
				$doc = new Document('proj', array('id'=>$id), $this->mysqli, $this->user);
				
				if(empty($pdoc['json'][0])) {
					# Create document entry
					$docid = $doc->create(
						$pdoc, $title, $abstr, $ref,
						null, null, null, $coeds, $categ, $visib
					);
				}
				else {
					list($docid) = $doc->upload($pdoc, 'make', null);
				}
				
				if(!empty($docid)) {
					$upd = "UPDATE Projects SET DocID='{$docid}' WHERE ID='{$id}'";
					
					if($this->mysqli->query($upd)) {
						# Associate document entry
						$doc->append(array('id'=>array($docid), 'val'=>array($pdoc['name'][0])), $id);
					}
				}
			}
			
			# Create and associate primary image entry
			if(!empty($pimg)) {
				# Instantiate image class
				$img = new Image('proj', array('id'=>$id), $this->mysqli, $this->user);
				
				if(empty($pimg['json'][0])) {
					# Create image entry
					$imgid = $img->create(
						$pimg, $title, $abstr, $ref, null, null, null, null, $coeds, $categ, $visib
					);
				}
				else {
					list($imgid) = $img->upload($pimg, 'make', null);
				}
				
				if(!empty($imgid)) {
					$upd = "UPDATE Projects SET ImgID='{$imgid}' WHERE ID='{$id}'";
					
					if($this->mysqli->query($upd)) {
						# Associate document entry
						$img->append(array('id'=>array($imgid), 'val'=>array($pimg['name'][0])), $id);
					}
				}
			}
			
			# Append microorganisms to project
			if(!empty($micros['val'])) {
				$micro = new Microorganism('proj', $this->mysqli, $this->user);
				$micro->append($micros, $id, true);
			}
			
			# Append authors to project
			if(!empty($authors["val"])) {
				$edtr = new Editor('author', $this->mysqli, $this->user);
				$edtr->append($authors, $id, true);
			}
			
			# Append sections to project
			if(!empty($secs["val"])) {
				$sec = new Section('proj', $this->mysqli, $this->user);
				$sec->create($id, $secs, $secfiles, $categ, $visib);
			}
			
			# Append sources to project
			if(!empty($srces['journ'])) {
				$this->appendSrce($srces, $id);
			}
			
			if(!empty($docs['tmp_name'])) {
				# Instantiate document class
				$doc = new Document('proj', array('id'=>$id), $this->mysqli, $this->user);
				$doc->upload($docs, 'make', null);
			}
			
			if(!empty($imgs['tmp_name'])) {
				# Instantiate image class
				$img = new Image('proj', array('id'=>$id), $this->mysqli, $this->user);
				$img->upload($imgs, 'make', null);
			}
			
			# Append files to project
			if(!empty($files['temp']['name'])) {
				$file = new File('proj', $this->mysqli, $this->user);
				$file->append($files['temp'], $id, $categ, $visib);
			}
			
			if(!empty($files['path']['name'])) {
				//to-do
			}
			
			# Append coeditors to project
			if(!empty($coeds['val'])) {
				$coed = new Editor('proj', $this->mysqli, $this->user);
				$coed->append($coeds, $id, false);
			}
		}
		# Error in inserting project
		else {
			$this->notif[] = "ERROR: ins proj";
		}
		
		# Notifications; an error has occurred
		if(!empty($this->notif)) {
			//echo '<pre>', var_dump($this->notif), '</pre>';
			return false;
		}
		
		# Created new project successfully
		return $id;
	} # function create
	
	/**
	* Update project
	* Update an existing project entry
	* 
	* @access public
	* @param string $id ID of project
	* @param string $title Title of project
	* @param string $abstr Abstract
	* @param mixed $authors Authors
	* @param mixed $micros Microorganisms
	* @param mixed $secs Sections
	* @param mixed $secfiles Files in each section
	* @param mixed $asecs Additional sections
	* @param mixed $asecfiles Files in additional sections
	* @param mixed $pic Profile picture
	* @param mixed $imgs Additional images
	* @param mixed $docs Additional documents
	* @param mixed $locs Additional locations
	* @param mixed $rsrcs Additional resources
	* @param mixed $srces Sources
	* @param mixed $asrcs Additional sources
	* @param mixed $notes Additional information
	* @param mixed $files Images and documents
	* @param mixed $coeds Coeditors
	* @param mixed $categ Category
	* @param mixed $visib Visibility
	* @param mixed $rauthors Removed authors
	* @param mixed $rmicros Removed microorganisms
	* @param mixed $rsecs Removed sections
	* @param mixed $rsecimgs Removed section images
	* @param mixed $rsecdocs Removed section documents
	* @param mixed $rimgs Removed images
	* @param mixed $rdocs Removed documents
	* @param mixed $rlocs Removed locations
	* @param mixed $rrsrcs Removed resources
	* @param mixed $rsrces Removed sources
	* @param mixed $rcoeds Removed coeditors
	* 
	* @return mixed id on success, false on failure
	*/
	public function update(
		$id, $title, $abstr, $authors, $micros, $secs, $secfiles, $asecs, $asecfiles, $pdoc, $pimg,
		$imgs, $docs, $locs, $rsrcs, $srces, $asrces, $notes, $ref, $files, $coeds, $categ, $visib,
		$rauthors, $rmicros, $rsecs, $rsecimgs, $rsecdocs, $rimgs, $rdocs, $rlocs, $rrsrcs, $rsrces, $rcoeds
	) {
		# Update project string
		$upd = "
			UPDATE Projects SET
				Title='".mysql_real_escape_string($title)."',
				Abstr=".(empty($abstr) ? 'NULL' : "'".mysql_real_escape_string($abstr)."'").", 
				Notes=".(empty($notes) ? 'NULL' : "'".mysql_real_escape_string($notes)."'").",
				Ref=".(empty($ref) ? 'NULL' : "'".mysql_real_escape_string($ref)."'").",
				".(empty($pdoc) ? '' : "DocID='{$pdoc}',")."
				".(empty($pimg) ? '' : "ImgPath='{$pimg}',")."
				UpdBy='{$this->user['id']}', UpdOn='".date('Y-m-d H:i:s:ms')."', UpdNo=UpdNo+1,
				Categ='{$categ}', Visib='{$visib}'
			WHERE ID='{$id}'
		";
		
		# Update project in mysql database
		if($this->mysqli->query($upd)) {
			if(!empty($pdoc)) {
				# Instantiate document class
				$doc = new Document('proj', array('id'=>$id), $this->mysqli, $this->user);
				
				if(empty($pdoc['json'][0])) {
					# Create document entry
					$docid = $doc->create(
						$pdoc, $title, $abstr, $ref,
						null, null, null, $coeds, $categ, $visib
					);
				}
				else {
					list($docid) = $doc->upload($pdoc, 'make', null);
				}
				
				if(!empty($docid)) {
					$upd = "UPDATE Projects SET DocID='{$docid}' WHERE ID='{$id}'";
					
					if($this->mysqli->query($upd)) {
						# Associate document entry
						$doc->append(array('id'=>array($docid), 'val'=>array($pdoc['name'][0])), $id);
					}
				}
			}
			
			# Create and associate primary image entry
			if(!empty($pimg)) {
				# Instantiate image class
				$img = new Image('proj', array('id'=>$id), $this->mysqli, $this->user);
				
				if(empty($pimg['json'][0])) {
					# Create image entry
					$imgid = $img->create(
						$pimg, $title, $abstr, $ref, null, null, null, null, $coeds, $categ, $visib
					);
				}
				else {
					list($imgid) = $img->upload($pimg, 'make', null);
				}
				
				if(!empty($imgid)) {
					$upd = "UPDATE Projects SET ImgID='{$imgid}' WHERE ID='{$id}'";
					
					if($this->mysqli->query($upd)) {
						# Associate document entry
						$img->append(array('id'=>array($imgid), 'val'=>array($pimg['name'][0])), $id);
					}
				}
			}
			
			# Authors
			$edtr = new Editor('author', $this->mysqli, $this->user);
			$edtr->operate($authors, $rauthors, $id, true);
			
			# Microorganisms
			$micro = new Microorganism('proj', $this->mysqli, $this->user);
			$micro->operate($micros, $rmicros, $id, true);
			
			# Sections
			$sec = new Section('proj', $this->mysqli, $this->user);
			$secnotif = $sec->update($id, $secs, $secfiles, $asecs, $asecfiles, $rsecs, $rsecimgs, $rsecdocs, $categ, $visib);
			if($secnotif!==true) {
				$this->notif[] = $secnotif;
			}
			
			# Images
			$img = new Image('proj', null, $this->mysqli, $this->user);
			$img->operate($imgs, $rimgs, $id);
			
			# Documents
			$doc = new Document('proj', array('id'=>$id), $this->mysqli, $this->user);
			$doc->operate($docs, $rdocs, $id);
			
			# Locations
			$loc = new Location('proj', $this->mysqli, $this->user);
			$loc->operate($locs, $rlocs, $id, array('categ'=>$categ, 'visib'=>$visib));
			
			# Resources
			$rsrc = new Resource('proj', $this->mysqli, $this->user);
			$rsrc->operate($rsrcs, $rrsrcs, $id);
			
			# Sources to be updated
			if(!empty($srces['journ'])) {
				$this->updateSrce($srces, $id);
			}
			
			# Add sources
			if(!empty($asrces['journ'])) {
				$this->appendSrce($asrces, $id);
			}
			
			# Sources to be removed
			if(!empty($rsrces)) {
				$this->removeSrce($rsrces, $id);
			}
			
			# Files
			if(!empty($files['temp']['name'])) {
				$file = new File('proj', $this->mysqli, $this->user);
				$file->append($files['temp'], $id, $categ, $visib);
			}
			
			if(!empty($files['path']['name'])) {
				//to-do
			}
			
			# Coeditors
			$coed = new Editor('proj', $this->mysqli, $this->user);
			$coed->operate($coeds, $rcoeds, $id, false);
		}
		# Error in updating project
		else {
			$this->notif[] = "Error in updating details of project {$title}.<br/>";
		}
		
		# Notifications found; Error occurred
		if(!empty($this->notif)) {
			//echo '<pre>', var_dump($this->notif), '</pre>';
			return false;
		}
		
		# Updated project successfully
		return true;
	} # function update
	
	/**
	* Delete project
	* Delete an existing project from the system
	* 
	* @access public
	* @param string $id Project ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function delete($id) {
		$del = "UPDATE Projects SET Remove='1' WHERE ID='{$id}'";
		
		if(!$this->mysqli->query($del)) {
			return false;
		}
	} # function delete
	
	/**
	* Recover project
	* Recover a deleted project
	* 
	* @access public
	* @param string $id Project ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function recover($id) {
		# Query string to recover project
		$del = "UPDATE Projects SET Remove='0' WHERE ID='{$id}'";
		
		# Recover project in the database
		$res = $this->mysqli->query($del);
		
		# Error occurred in deletion
		if(!$res) {
			echo "ERROR: recover";
			return false;
		}
		
		# Successfully recovered project
		return true;
	} # function recover
	
	/**
	* Upload JSON inputs for multiple projects with images and documetns
	* Upload json input of projects to be added or updated
	* 
	* @access public
	* @param mixed $minput JSON inputs
	* @param string $action Action to be performed on uploaded inputs
	* @param mixed $opts Additional parameters
	* 
	* @return array Results on each input processed
	*/
	public function uploadMany($minput, $action, $opts) {
		$results = array();
		
		foreach($minput['tmp_name']['multi'] as $i => $path) {
			$inpath = 'data/tmp/'.$this->user['id'].'-'.uniqid();
			$name = $minput['name']['multi'][$i];
			$trname = Tool::trimout($name, 25);
			$input = $inpath.'/'.$name;
			
			# Make temporary directory and move file
			if(!mkdir($inpath, 0777, true) or !move_uploaded_file($path, $input)) {
				$results[$i] = false;
				$results['error'][] = $name;
				return false;
			}
			
			$zip = new ZipArchive;
			
			if(true===$zip->open($input)) {
				$extpath = $inpath.'/'.$trname.'-'.uniqid();
				
				$zip->extractTo($extpath);
				$zip->close();
				
				unlink($input);
				//echo '<h3 style="color:darkgreen">Yeah!</h3>';
			}
			else {
				//echo '<h3 style="color:darkred">Booh!</h3>';
			}
			
			$found = false;
			
			if($handle = opendir($extpath)) {
				while((false!==($file = readdir($handle))) and !$found) {
					if(strtolower($this->getExt($file))=='.json') {
						$inputs['tmp_name'][] = $extpath.'/'.$file;
						$inputs['name'][] = $file;
						$inputs['path'][] = $extpath;
						
						$results[$i] = $this->upload($inputs, $action, $opts);
						
						$found = true;
					}
				}
				
				closedir($handle);
			}
			
			rmdir($inpath);
		}
		
		return $results;
	} # function uploadMany
	
	/**
	* Upload JSON input for project 
	* Upload json input of projects to be added or updated
	* 
	* @access public
	* @param mixed $inputs JSON inputs
	* @param string $action Action to be performed on uploaded inputs
	* @param mixed $opts Additional parameters
	* 
	* @return array Results on each input processed
	*/
	public function upload($inputs, $action, $opts) {
		$results = array();
		
		# Scan each json file
		foreach($inputs['tmp_name'] as $i => $path) {
			$inpath = 'data/tmp/'.$this->user['id'].'-'.uniqid();
			$input = $inpath.'/'.Tool::trimout($inputs['name'][$i], 25);
			
			# Make temporary directory and move file
			if(!mkdir($inpath, 0777, true)) {
				continue;
			}
			
			if(is_uploaded_file($path)) {
				if(!move_uploaded_file($path, $input)) {
					continue;
				}
			}
			else if(!file_exists($path) or !copy($path, $input)) {
				rmdir($inpath);
				continue;
			}
			
			# Decode json contents
			$json = json_decode(utf8_encode(preg_replace( '/\s+/', ' ', file_get_contents($input))));
			
			# Title or abstract is not found
			if(!$json or empty($json->title) or empty($json->abstract)) {
				$results[$i] = false;
				$results['error'][] = $inputs['name'][$i];
				unlink($input);
				rmdir($inpath);
				continue;
			}
			
			# Title and Abstract
			$title = $json->title;
			$abstr = $json->abstract;
			
			# Notes, References
			$notes = empty($json->notes) ? null : $json->notes;
			$ref = empty($json->references) ? null : $json->references;
			
			# Authors
			$authors = array();
			if(!empty($json->authors)) {
				foreach($json->authors as $auth) {
					$authors['val'][] = empty($auth->email) ? implode(',', array($auth->name[0], $auth->name[1], $auth->name[2])) : $auth->email;
					$authors['id'][] = empty($auth->id) ? null : $auth->id;
				}
			}
			
			# Microorganisms
			$micros = array();
			if(!empty($json->microorganisms)) {
				foreach($json->microorganisms as $micro) {
					$micros['val'][] = empty($micro->name) ? null : $micro->name;
					$micros['auth'][] = empty($micro->authors) ? null : $micro->authors;
					$micros['id'][] = empty($auth->id) ? null : $auth->id;
				}
			}
			
			# Sections
			$secs = array();
			if(!empty($json->sections)) {
				$j = 0;
				foreach($json->sections as $sec) {
					if(!empty($sec->header)) {
						$secs['val'][$j]['head'] = $sec->header;
						$secs['val'][$j]['cont'] = empty($sec->content) ? null : $sec->content;
						$secs['id'][$j] = empty($sec->id) ? null : $sec->id;
						$j++;
					}
				}
			}
			
			# Files in section
			$secfiles = null;
			
			# Primary files
			$pimg = null;
			$pdoc = null;
			$primg = null;
			$pimg = null;
			$prdoc = null;
			$pdoc = null;
			
			if(!empty($json->primary)) {
				if(!empty($json->primary->image)) {
					$primg = $json->primary->image;
				}
				
				if(!empty($json->primary->document)) {
					$prdoc = $json->primary->document;
				}
			}
			
			$ispath = empty($inputs['path'][$i]);
			
			# Images
			$imgs = array();
			if(!($ispath or !is_dir($inputs['path'][$i].'/imgs'))) {
				$imgpath = $inputs['path'][$i].'/imgs';
				$files = scandir($imgpath);
				
				foreach($files as $file) {
					if(is_dir($file)) {
						continue;
					}
					
					$filepath = $imgpath.'/'.$file;
					
					if(strtolower($this->getExt($file))=='.json') {
						if($primg==$file) {
							$pimg['name'][] = $file;
							$pimg['type'][] = 'application/json';
							$pimg['tmp_name'][] = $filepath;
							$pimg['error'][] = 0;
							$pimg['size'][] = filesize($filepath);
							$pimg['json'][] = 1;
							$pimg['path'][] = $imgpath;
						}
						else {
							$imgs['name'][] = $file;
							$imgs['type'][] = 'application/json';
							$imgs['tmp_name'][] = $filepath;
							$imgs['error'][] = 0;
							$imgs['size'][] = filesize($filepath);
							$imgs['json'][] = 1;
							$imgs['path'][] = $imgpath;
						}
					}
					// else {
						// $imgs['name'][] = $file;
						// $imgs['type'][] = $this->getType($filepath);
						// $imgs['tmp_name'][] = $filepath;
						// $imgs['error'][] = 0;
						// $imgs['size'][] = filesize($filepath);
					// }
				}
			}
			
			# Documents
			$docs = array();
			if(!($ispath or !is_dir($inputs['path'][$i].'/docs'))) {
				$docpath = $inputs['path'][$i].'/docs';
				$files = scandir($docpath);
				
				foreach($files as $file) {
					if(is_dir($file)) {
						continue;
					}
					
					$filepath = $docpath.'/'.$file;
					
					if(strtolower($this->getExt($file))=='.json') {
						if($prdoc==$file) {
							$pdoc['name'][] = $file;
							$pdoc['type'][] = 'application/json';
							$pdoc['tmp_name'][] = $filepath;
							$pdoc['error'][] = 0;
							$pdoc['size'][] = filesize($filepath);
							$pdoc['json'][] = 1;
							$pdoc['path'][] = $docpath;
						}
						else {
							$docs['name'][] = $file;
							$docs['type'][] = 'application/json';
							$docs['tmp_name'][] = $filepath;
							$docs['error'][] = 0;
							$docs['size'][] = filesize($filepath);
							$docs['json'][] = 1;
							$docs['path'][] = $docpath;
						}
					}
					// else {
						// $docs['name'][] = $file;
						// $docs['type'][] = $this->getType($filepath);
						// $docs['tmp_name'][] = $filepath;
						// $docs['error'][] = 0;
						// $docs['size'][] = filesize($filepath);
					// }
				}
			}
			
			# Locations
			$locs = array();
			if(!empty($json->locations)) {
				foreach($json->locations as $loc) {
					$locs['val'][] = empty($loc->name) ? null : $loc->name;
					$locs['coord'][] = (empty($loc->coords[0]) or empty($loc->coords[1])) ? null : 'yes';
					$locs['id'][] = empty($loc->id) ? null : $loc->id;
				}
			}
			
			# Resources
			$rsrcs = array();
			if(!empty($json->resources)) {
				foreach($json->resources as $rsrc) {
					$rsrcs['title'][] = empty($rsrc->title) ? null : $rsrc->title;
					$rsrcs['notes'][] = empty($rsrc->notes) ? null : $rsrc->notes;
					$rsrcs['links'][] = empty($rsrc->links) ? null : $rsrc->links;
					$rsrcs['id'][] = empty($rsrc->id) ? null : $rsrc->id;
				}
			}
			
			# Sources
			$srces = array();
			if(!empty($json->sources)) {
				foreach($json->sources as $srce) {
					$srces['journ'][] = empty($srce->journal) ? null : $srce->journal;
					$srces['year'][] = empty($srce->year) ? null : $srce->year;
					$srces['vol'][] = empty($srce->volume) ? null : $srce->volume;
					$srces['num'][] = empty($srce->number) ? null : $srce->number;
					$srces['page'][] = empty($srce->page) ? null : $srce->page;
				}
			}
			
			# Files
			$files['path'] = array();
			if(!empty($json->files)) {
				foreach($json->files as $file) {
					$files['path']['name'][] = empty($file->path) ? null : $file->path;
				}
			}
			$files['temp'] = isset($_FILES['file']) ? $_FILES['file'] : null;
			
			# Settings
			$coeds = array();
			$categ = 'ADV';
			$visib = 'PRV';
			if(!empty($json->settings)) {
				$st = $json->settings;
				
				# Coeditors
				if(!empty($st->coeditors)) {
					foreach($st->coeditors as $coed) {
						$coeds['val'][] = empty($coed->email) ? $coed->name : $coed->email;
						$coeds['id'][] = empty($coed->id) ? '' : $coed->id;
					}
				}
				
				# Category
				if(!empty($st->category)) {
					switch(strtolower($st->category)) {
						case 'advanced':
						case 'adv':
							$categ = 'ADV';
						break;
						
						case 'basic':
						case 'bsc':
							$categ = 'BSC';
						break;
					}
				}
				
				# Visibility
				if(!empty($st->visibility)) {
					switch(strtolower($st->visibility)) {
						case 'private':
						case 'prv':
							$visib = 'PRV';
						break;
						
						case 'public':
						case 'pub':
							$visib = 'PUB';
						break;
					}
				}
			}
			
			# Make or update
			switch($action) {
				# Create project
				case 'make':
					# Search project if existing
					list($res, $size) = $this->search($title, array('c'=>'exact'), 0, 10);
					
					# Project is not found, create
					if(empty($size)) {
						$results[$i] = $this->create(
							$title, $abstr, $authors, $micros, $secs, $secfiles, $pimg, $pdoc,
							$srces, $notes, $ref, $imgs, $docs, $files, $coeds, $categ, $visib
						);
					}
					# Project is found, update
					else {
						$proj = $res->fetch_object();
						
						$results[$i] = $this->update(
							$proj->ID, $title, $abstr, $authors, $micros,
							$secs, $secfiles, $secs, $secfiles, empty($idt->photo) ? null : $idt->photo, $pdoc,
							$imgs, $docs, $locs, $rsrcs, $srces, $srces, $notes, $ref, $files, $coeds, $categ, $visib,
							null, null, null, null, null, null, null, null, null, null, null
						);
					}
				break;
				
				# Update project
				case 'edit':
					# ID is not given
					if(empty($opts['id'])) {
						# Search for project ID
						list($res, $size) = $this->search($opts['id'], array('c'=>'id'), 0, 10);
						if(!empty($size)) {
							$proj = $res->fetch_object();
							$opts['id'] = $proj->ID;
						}
					}
					
					$results[$i] = $this->update(
						$opts['id'], $title, $abstr, $authors, $micros,
						$secs, $secfiles, $secs, $secfiles, empty($idt->photo) ? null : $idt->photo, $pdoc,
						$imgs, $docs, $locs, $rsrcs, $srces, $srces, $notes, $ref, $files, $coeds, $categ, $visib,
						null, null, null, null, null, null, null, null, null, null, null
					);
				break;
			}
			
			# Error in creating or updating project
			if($results[$i]===false) {
				$results['error'][] = $inputs['name'][$i];
			}
			
			Tool::deleteAllFiles($inputs['path'][$i], true);
			
			# Remove temporary file and directory
			unlink($input);
			rmdir($inpath);
		}
		
		# Return results
		return $results;
	} # function upload
	
	/**
	* Get file type
	* Retrieves a file's type
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getType($name) {
		switch(strtolower($this->getExt($name))) {
			case '.jpg':
			case '.jpeg':
				$type = 'image/jpeg';
			break;
			
			case '.gif':
				$type = 'image/gif';
			break;
			
			case '.pdf':
				$type = 'application/pdf';
			break;
			
			default:
				$type = null;
			break;
		}
		
		return $type;
	}
	
	/**
	* Get file extension
	* Retrieves a file's extension
	* 
	* @access public
	* @param string $name Name of file
	* 
	* @return string File's extension
	*/
	public function getExt($name) {
		return strtolower(substr($name, strrpos($name, '.')));
	}
	
	/**
	* Download project
	* Download all allowed details of a project
	* 
	* @access public
	* @param string $id Project ID
	*/
	public function download($id) {
		# Search project
		list($res, $size) = $this->search($id, array('c'=>'id'), null, null);
		
		# Redirect if not found
		if(empty($size)) {
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?proj=view&fail=get&id='.$id.'"'); return false;
		}
		
		$proj = $res->fetch_object();
		
		# Get settings for project
		$sett = new Setting('proj', null, $this->mysqli, $this->user);
		$cond = '';
		
		# Category is Basic
		if($proj->Categ=='BSC') {
			$cond = "AND T1.Categ='BSC' AND T1.Visib='PUB'";
		}
		# User is not permitted to download
		elseif(!$sett->verify($id)) {
			header('refresh: 0.1; url="http://localhost/microwebph/main.php?proj=view&fail=get&id='.$id.'"'); return false;
		}
		
		# Create PDF file
		$file = new FPDF();
		$file->SetTitle($proj->Title.' - MicroWebPH');
		$file->SetAuthor('MicroWebPH (c) 2011');
		$file->AcceptPageBreak();
		$file->AddPage();
		
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(72,61,139);
		$file->Write(5, 'MicroWebPH', 'http://localhost/microwebph/');
		$file->SetFont('helvetica', '', 10); $file->SetTextColor(150,150,150);
		$file->Write(5, ' An Online Repository, Management and Retrieval System for Information on Microorganisms'); $file->Ln(); $file->Ln();
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Project title
		$file->SetFont('helvetica', 'b', 12); $file->SetTextColor(72,61,139);
		$file->Write(5, $proj->Title, "http://localhost/microwebph/main.php?proj=view&id={$id}"); $file->Ln(); $file->Ln();
		
		# Project abstract
		$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
		$file->Write(5, 'Abstract '); $file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0); $file->Ln();
		$file->Write(5, $proj->Abstr); $file->Ln(); $file->Ln();
		
		# Editors
		list($res, $size) = $this->retrieve('edtr', $id, null, $cond, '');
		if(!empty($size)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Authors'); $file->SetTextColor(0,0,0); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			# List of authors
			while($auth = $res->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(0,0,0);
				$file->Write(5, $auth->Lname.', '.$auth->Fname.', '.$auth->Mname); $file->Ln();
			}
		} $file->Ln();
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Sections
		list($secs, $size) = $this->retrieve('sec', $id, null, $cond, '');
		if(!empty($size)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Sections'); $file->SetTextColor(0,0,0); $file->Ln();
			$i = 1;
			
			# List all sections and contents
			while($sec = $secs->fetch_object()) {
				$file->SetFont('helvetica', '', 10); $file->SetX(10);
				$file->Write(5, $i++.'. '.$sec->Header); $file->Ln();
				
				if(!empty($sec->Content)) {
					$file->SetFont('helvetica', '', 10); $file->SetX(20);
					$file->Write(5, $sec->Content); $file->Ln();
				}
			}
			$file->Ln();
		}
		
		# Notes
		if(!empty($proj->Notes)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Notes'); $file->SetFont('helvetica', ''); $file->SetTextColor(0,0,0); $file->Ln();
			$file->Write(5, $proj->Notes); $file->Ln(); $file->Ln();
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Microorganisms
		list($micros, $size) = $this->retrieve('micro', $id, null, $cond, '');
		if(!empty($micros)) {
			$file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(5, 'Microorganisms'); $file->SetTextColor(0,0,0); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			# List of microorganisms
			while($micro = $micros->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $micro->Name, "http://localhost/microwebph/main.php?micro=view&id={$micro->ID}"); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Images
		list($imgs, $size) = $this->retrieve('img', $id, null, $cond, '');
		if(!empty($size)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(8, 'Images'); $file->Ln(); $file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
			
			# List of images
			while($img = $imgs->fetch_object()) {
				$file->Image($img->Thumb, null, null, null, 50);
				
				$file->SetFont('helvetica', '', 10); $file->SetTextColor(72,61,139);
				$file->Write(5, $img->Title.' ', 'http://localhost/microwebph/main.php?img=view&id='.$img->ID); $file->Ln();
				
				# Image notes
				if(!empty($img->Notes)) {
					$file->SetTextColor(0,0,0);
					$file->Write(5, $img->Notes); $file->Ln();
				}
				$file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Documents
		list($docs, $size) = $this->retrieve('doc', $id, null, $cond, '');
		if(!empty($size)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(8, 'Documents'); $file->Ln();
			$i = 1;
			$file->SetFont('helvetica', '', 10);
			# Links to documents
			while($doc = $docs->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $doc->Title, "http://localhost/microwebph/main.php?doc=view&id={$doc->ID}"); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Locations
		list($locs, $sizeloc) = $this->retrieve('loc', $id, null, $cond, '');
		if(!empty($sizeloc)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(8, 'Locations'); $file->Ln();
			$file->SetFont('helvetica', '', 10);
			$i = 1;
			# List of locations
			while($loc = $locs->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(72,61,139);
				$file->Write(5, $loc->Name.(empty($loc->Notes) ? '' : ': '.$loc->Notes), "http://localhost/microwebph/main.php?loc=view&id={$loc->ID}"); $file->Ln();
			}
		}
		
		# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
		
		# Sources
		list($srces, $sizeSrce) = $this->retrieve('srce', $id, null, $cond, '');
		if(!empty($sizeSrce)) {
			$file->Ln(); $file->SetFont('helvetica', 'b', 10); $file->SetTextColor(80,80,80);
			$file->Write(8, 'Sources'); $file->Ln();
			$file->SetFont('helvetica', '', 10); $file->SetTextColor(0,0,0);
			$i = 1;
			while($srce = $srces->fetch_object()) {
				$file->SetTextColor(80,80,80); $file->Write(5, $i++.'. '); $file->SetTextColor(0,0,0);
				$texts = '';
				if(!empty($srce->Year))	$texts .= '. yr. '.$srce->Year; # Year
				if(!empty($srce->Vol)) $texts .= '. vol. '.$srce->Vol; # Volume
				if(!empty($srce->Num)) $texts .= '-'.$srce->Num; # Number
				if(!empty($srce->Page))	$texts .= ' (pg. '.$srce->Page.')'; #Pages
				$file->Write(5, $srce->Journ.$texts); $file->Ln();
			}
		}
		
		# Output file
		$file->Output(str_replace(' ', '_', Tool::trimout($proj->Title))."-microwebph.pdf", 'i');
	} # function download
	
	/**
	* Append sources
	* Append new source to project
	* 
	* @access public
	* @param array $srces Sources
	* @param string $id Project ID
	*/
	public function appendSrce($srces, $id) {
		# Iterate through each source
		foreach($srces['journ'] as $i => $journ) {
			# Empty, skip
			if(empty($journ)) continue;
			
			$sid = Tool::generateID('src');
			$journ = mysql_escape_string($journ);
			$year = empty($srces['year'][$i]) ? 'NULL' : "'".$srces['year'][$i]."'";
			$vol = empty($srces['vol'][$i]) ? 'NULL' : "'".$srces['vol'][$i]."'";
			$num = empty($srces['num'][$i]) ? 'NULL' : "'".$srces['num'][$i]."'";
			$page = empty($srces['page'][$i]) ? 'NULL' : "'".$srces['page'][$i]."'";
			
			# Create new source
			$ins = "
				INSERT INTO ProjSources VALUES (
					'{$id}', '{$sid}', '{$journ}', {$year}, {$vol}, {$num}, {$page},
					NULL, NULL, '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
				)
			";
			
			# Perform insert
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "<br/>ERROR ins src";
			}
		}
	} # function appendSrce
	
	/**
	* Update sources
	* Update sources linked to project
	* 
	* @access public
	* @param array $srces Sources
	* @param string $id Project ID
	*/
	public function updateSrce($srces, $id) {
		# Iterate through each source
		foreach($srces['journ'] as $i => $journ) {
			# Empty, skip
			if(empty($srces['id'][$i])) continue;
			
			$sid = $srces['id'][$i];
			$journ = mysql_escape_string($journ);
			$year = empty($srces['year'][$i]) ? 'NULL' : "'".$srces['year'][$i]."'";
			$vol = empty($srces['vol'][$i]) ? 'NULL' : "'".$srces['vol'][$i]."'";
			$num = empty($srces['num'][$i]) ? 'NULL' : "'".$srces['num'][$i]."'";
			$page = empty($srces['page'][$i]) ? 'NULL' : "'".$srces['page'][$i]."'";
			
			# Update source
			$upd = "
				UPDATE ProjSources SET
					Journ='{$journ}', Year={$year}, Vol={$vol}, Num={$num}, Page={$page},
					UpdBy='{$this->user['id']}', UpdOn='".date('Y-m-d H:i:s:ms')."', UpdNo=UpdNo+1
				WHERE PID='{$id}' AND CID='{$sid}'
			";
			
			# Perform update
			if(!$this->mysqli->query($upd)) {
				$this->notif[] = "<br/>ERROR upd src";
			}
		}
	} # function updateSrce
	
	/**
	* Remove sources
	* Remove sources linked to project
	* 
	* @access public
	* @param array $srcid Sources
	* @param string $id Project ID
	*/
	public function removeSrce($srcid, $id) {
		$del = "DELETE FROM ProjSources WHERE PID='{$id}' AND CID IN ('".implode("', '", $srcid)."')";
		
		# Remove source
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: delete source<br/>";
		}
	} # function removeSrce
	
	/**
	* Process appended and removed projects
	* Process all projects associated with an area
	* which are to be appended or removed
	* 
	* @access public
	* @param array $addl Projects to be appended
	* @param array $rmvl Projects to be removed
	* @param string $id ID of area
	*/
	public function operate($addl, $rmvl, $id) {
		if(!empty($addl["val"])) $this->append($addl, $id);
		if(!empty($rmvl)) $this->remove($rmvl, $id);
	}
	
	/**
	* Append projects
	* Append projects associated to that area
	* 
	* @access public
	* @param array $addl Projects to be appended
	* @param string $id ID of area
	*/
	public function append($addl, $id) {
		# iterate through each project
		foreach($addl['val'] as $i => $value) {
			# Empty project, skip
			if(empty($value)) continue;
			
			$ins = '';
			
			# Append project to area
			if(!empty($addl['id'][$i])) {
				$ins = "INSERT INTO {$this->table} VALUES ('{$addl['id'][$i]}', '{$id}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			}
			# search project for its ID
			else {
				$res = $this->mysqli->query("SELECT ID FROM Projects WHERE Title='{$value}'");
				
				# Project found
				if($res and !empty($res->num_rows)) {
					$proj = $res->fetch_object();
					$ins = "INSERT INTO {$this->table} VALUES ('{$proj->ID}', '{$id}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
				}
			}
			
			# Append project if not empty
			if(!empty($ins)) {
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = "ERROR: ins area-proj {$id} $value.<br/>";
				}
			}
		}
	} # function append
	
	/**
	* Remove projects
	* Remove projects associated to that area
	* 
	* @access public
	* @param array $rmvl Projects to be removed
	* @param string $id ID of area
	*/
	public function remove($rmvl, $id) {
		$del = "DELETE FROM {$this->table} WHERE PID='{$id}' AND CID IN ('".implode("', '", $rmvl)."')";
		
		# Remove project
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: rem proj<br/>";
		}
	}
	
	/**
	* Display all projects
	* Retrieve all contents of projects on a page
	* 
	* @access public
	* @param array $queries IDs of projects
	*/
	public function displayAll($queries, $opts) { ?>
		<output> <?php
			if($results = $this->search($queries, $opts, 0, 10)) {
				while($result = $results[0]->fetch_object()) {
					$this->displayContent($result, false);
				}
			} ?>
		</output> <?php
	}
	
	/**
	* Guess project
	* Provides a list of projects (guess) on user input
	* Makes selection of project and id faster
	* 
	* @access public
	* @param mixed $projs List of projects in search results
	*/
	public function guess($query) {
		# Search for locations matching the query string and constrains passed
		$projs = $this->search($query, $_REQUEST, 0, 10);
		
		# Location is not found
		if(!$projs or empty($projs[1])) {
			return false;
		}
		
		# List of projects
		while($proj = $projs[0]->fetch_object()) { ?>
			<div class="guess proj" tabindex="0" title="<?php echo $proj->Title ?>"
				data-id="<?php echo $proj->ID ?>" data-value="<?php echo $proj->Title ?>">
				<a href="main.php?proj=view&id=<?php echo $proj->ID ?>"> <?php
					echo Tool::truncate($proj->Title, 50); ?></a>
			</div> <?php
		}
		
		if($_REQUEST['s']=='true') { ?>
			<div class="guess-header proj query">
				<a href="main.php?proj=view&q=<?php echo urlencode($query) ?>" target="_blank" title="<?php echo $query ?>"><?php echo Tool::truncate($query, 30) ?></a>
				<span class="right bold none" title="<?php echo ($found = $projs[0]->num_rows.' of '.$projs[1]).' items found' ?>"><?php echo $found ?></span>
			</div> <?php
		}
	} # function guess
	
	/**
	* Fetch projects
	* Fetch projects associated with an area
	* 
	* @access public
	* @param string $id ID of area
	* @param int $start Start of return results
	*/
	public function fetch($id, $start) {
		# Fetch projects assoc. in an area
		$sel = "
			SELECT T1.* FROM Projects AS T1 INNER JOIN {$this->table} AS T2
				ON T1.ID=T2.PID AND T2.CID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
		";
		
		$res = $this->mysqli->query($sel);
		
		if($res and !empty($res->num_rows)) { ?>
			<output style="display:none"> <?php
				while($proj = $res->fetch_object()) { ?>
					<li class="proj">
						<a data-title="<?php echo $proj->Title ?>" data-doc="<?php
							$sel = "SELECT Path FROM Documents WHERE ID='{$proj->DocID}'";
							$res = $this->mysqli->query($sel);
							
							if($res and $res->num_rows > 0) {
								$doc = $res->fetch_object();
								echo $doc->Path;
							}
						?>" href="main.php?proj=view&id=<?php echo $proj->ID ?>" title="<?php echo $proj->Title ?>"><?php echo $proj->Ref ?></a>
					</li> <?php
				} ?>
			</output> <?php
		}
	} # function fetch
	
	/**
	* Retrieve details
	* Get all details associated with projects to be displayed
	* 
	* @access private
	* @param string $area Area where project is associated
	* @param string $id ID of project
	* @param mixed $proj Project object
	* @param string $cond Additional constraints
	* @param string $limit Limit to search results
	* 
	* @return mixed Returned results on search
	*/
	private function retrieve($area, $id, $proj, $cond, $limit) {
		$selSize = "SELECT FOUND_ROWS()";
		
		# Retrieve project-related contents
		switch($area) {
			# Microorganism
			case 'micro':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 INNER JOIN ProjMicros AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Images
			case 'img':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN ProjImgs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Documents
			case 'doc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Documents AS T1 INNER JOIN ProjDocs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Locations
			case 'loc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Locations AS T1 INNER JOIN ProjLocs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Resources
			case 'rsrc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 INNER JOIN ProjRsrcs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Sources
			case 'srce':
				$sel = "SELECT * FROM ProjSources WHERE PID='{$id}'";
			break;
			
			# Editors
			case 'edtr':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Editors AS T1 INNER JOIN ProjAuthors AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' {$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Sections
			case 'sec':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM ProjSections WHERE PID='{$id}' ORDER BY CrtOn
				";
			break;
			
			# Section images
			case 'sec-img':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN ProjSecImgs AS T2
						ON T1.ID=T2.ImgID AND T2.PID='{$id[0]}' AND T2.CID='{$id[1]}' AND T1.Remove='0'
					{$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
			
			# Section documents
			case 'sec-doc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Documents AS T1 INNER JOIN ProjSecDocs AS T2
						ON T1.ID=T2.DocID AND T2.PID='{$id[0]}' AND T2.CID='{$id[1]}' AND T1.Remove='0'
					{$cond} ORDER BY T2.CrtOn {$limit}
				";
			break;
		}
		
		# Retrieve in mysql
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results and size
		return array($res, $size[0]);
	} # function retrieve
	
	/**
	* Display main projects stage
	* List all projects in the main page
	* 
	* @access public
	* @param mixed $projs List of projects from returned search results
	* @param integer $size Size of rows from returned search results
	* @param string $query Query string that was searched for
	* @param array $opts Optional parameters
	* @param integer $start Starting row in mysql returned results
	*/
	public function displayMain($projs, $size, $query, $opts, $start) {
		# One project is to be viewed
		$view = $projs->num_rows==1;
		# Page number
		$page = ceil(($start+1)/10);
		# Prepare URL variables
		$optstr = Tool::optstrify($opts); ?>
		
		<div id="side"> <?php
			# Show Back and Next buttons for navigation ?>
			<div id="navis"> <?php
				# Links to previous ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($query) ? '' : '&q='.$query).(empty($start) ? '&s=0' : '&s='.(intval($start)-10)) ?>"
					class="navi ui ui-button prev <?php if(empty($start)) echo 'disabled' ?>" tabindex="-1" title="Previous 10 items"></a> <?php
				# Links to next ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($start) ? '&s=10' : '&s='.(intval($start)+10)) ?>"
					class="navi ui ui-button next <?php if(($projs->num_rows<10) or ($projs->num_rows*$page)>=$size) { echo 'disabled'; } ?>" tabindex="-1" title="Next 10 items"></a>
			</div> <?php
			
			# Knobs to stage a project ?>
			<div id="knobs"> <?php $i = 1;
				while($proj = $projs->fetch_object()) {
					# Contains data query title, id, tool (tooltip help)
					$title = Tool::truncate($trtitle = $proj->Title, 80);	?>
					<div id="knob<?php echo $proj->ID ?>" class="knob proj <?php if($view) echo "lock" ?>" data-query="<?php echo $proj->ID ?>"
						data-id="<?php echo $proj->ID ?>" data-tool="{'head':'<b class=\'cool\'><?php echo $title ?></b>','x':'l'}">
						<?php echo $i++; ?>
					</div> <?php
				} ?>
			</div>
		</div> <?php
		
		# Labels stage items ?>
		<div id="hnotif" class="escape"> <?php
			# Shows metadata of all searched items ?>
			<span id="query" class="escape iblock" data-tool="{'head':'<?php echo ($all = (empty($query) and empty($opts['q']))) ? "All projects" : (empty($opts['q']) ? $trtitle : $opts['q']) ?>','x':'l'}"
				<?php if(!($nctrl = empty($_COOKIE['ctrl']['search']))) { echo 'style="width:400px"'; } ?>>
				<?php echo ($all ? "All projects" : ($view ? $title : $query)) ?>
			</span>
			
			<span>
				<span id="search-ctrls" <?php if($nctrl) { echo 'class="none"'; } ?>> <?php
					# No. of returned results
					echo '<span id="numresults">Showing '.($projs->num_rows).' of <b>'.$size.'</b> result(s)</span> on page ';
					
					# Many microorganisms are to be viewed
					$ob = isset($_REQUEST['ob']); $of = true;
					unset($opts['ob']); unset($opts['oa']);
					$optstr = Tool::optstrify($opts);
					
					# Prepare filter options and page selector ?>
					<select id="main-page" class="page navi" data-tool="{'head':'Page'}"> <?php
						for($i=0, $x=$size/10; $i<$x; $i++)	echo "<option ".((isset($opts['s']) and $opts['s']==($i*10)) ? 'selected="selected"' : '').'value="main.php?'.$optstr.(empty($query) ? '' : '&q='.$query).'&s='.($i*10).'">'.($i+1).'</option>';?>
					</select> sorted by <?php
					
					# Prepare filter options ?>
					<select class="navi" data-tool="{'head':'Sort'}">
						<option value="main.php?<?php echo $optstr ?>&ob=title&oa=asc" <?php if($ob and $_REQUEST['ob']=='title') { echo 'selected="selected"'; $of = false; } ?>>Title</option>
						<option value="main.php?<?php echo $optstr ?>&ob=abstr&oa=asc" <?php if($ob and $_REQUEST['ob']=='abstr') { echo 'selected="selected"'; $of = false; } ?>>Abstract</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crtby&oa=asc" <?php if($ob and $_REQUEST['ob']=='crtby') { echo 'selected="selected"'; $of = false; } ?>>Author</option>
						<option value="main.php?<?php echo $optstr ?>&ob=updon&oa=desc" <?php if($ob and $_REQUEST['ob']=='updon') { echo 'selected="selected"'; $of = false; } ?>>Last edited</option>
						<option value="main.php?<?php echo $optstr ?>&ob=shron&oa=desc" <?php if($ob and $_REQUEST['ob']=='shron') { echo 'selected="selected"'; $of = false; } ?>>Last shared</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crton&oa=desc" <?php if($ob and $_REQUEST['ob']=='crton') { echo 'selected="selected"'; $of = false; } ?>>Date created</option>
						<option value="main.php?<?php echo $optstr ?>&ob=id&oa=asc" <?php if($ob and $_REQUEST['ob']=='id') { echo 'selected="selected"'; $of = false; } ?>>ID</option>
					</select>
				</span>
				<span <?php if(!$nctrl) { echo 'class="none"'; } ?>><?php echo "$projs->num_rows of <b>$size</b> result(s) on page <b>$page</b>";  ?></span> <button type="button" class="navi-details <?php echo (!$nctrl ? 'selected' : '') ?>" data-tool="{'head':'Search controls'}"></button>
			</span>
		</div>  <?php
		
		# Contains all project headers ?>
		<div id="stage"> <?php
			# Reset pointer to first row in mysql result
			$projs->data_seek(0);
			
			# List all projects on its own entry page
			while($proj = $projs->fetch_object()) {
				# Show first the heading of each project
				$this->displayHeading($proj, $view ? true : false);
			} ?>
		</div> <?php
	}
	
	/**
	* Display a project heading
	* Displays a heading for each project in the results
	* which contains the project's scientific name
	* 
	* @access public
	* @param mixed $proj Contains all details of the project
	* @param boolean $cont Checks if content is to be displayed too
	*/
	public function displayHeading($proj, $cont) {
		# List a project first as an area with a header that can be selected/clicked by the user in the stage
		# Data included: head (title), id (project id)
		?> <div id="area<?php echo $proj->ID ?>" class="stage area proj" data-head="<?php echo $proj->Title ?>">
			<div class="div-header proj <?php echo $cont ? "active lock" : "heading" ?>" data-id="<?php echo $proj->ID ?>" data-content="proj"
				<?php if(strlen($proj->Title)>125) echo 'data-tool="{\'head\':\''.$proj->Title.'\',\'x\':\'l\'}"' ?>>
				<a href="main.php?proj=view&id=<?php echo $proj->ID ?>" class="title" tabindex="-1">
					<?php echo Tool::truncate($proj->Title, 125) ?></a>
			</div> <?php
			
			# Show project's contents if necessary
			if($cont) {
				$this->displayContent($proj, $cont);
			} ?>
		</div> <?php
	}
	
	/**
	* Display contents of project
	* Displays the contents of a project, from its title
	* to its associated items in other areas of the system
	* 
	* @access public
	* @param mixed $proj Contains all details of the project
	* @param boolean $cont Checks if only one project is found in results
	*/
	public function displayContent($proj, $cont) { ?>
		<div class="div-content">
			<form class="proj" method="post" action="process.php?proj=edit" enctype="multipart/form-data" novalidate="novalidate">
			<div class="div-upper">
				<div class="div-body">
					<div class="div-peel"><b>Title</b></div>
					<div class="div-case">
						<textarea name="title" class="title reqd read" readonly="readonly" rows="<?php echo ceil(strlen($proj->Title)/100) ?>"><?php echo $proj->Title ?></textarea>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($proj->Abstr) or $proj->Abstr=='NULL')) ? "on" : "off open" ?> next abstr"><b>Abstract</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="abstr" class="abstr reqd read" rows="<?php echo empty($proj->Abstr) ? '5' : ceil(strlen($proj->Abstr)/100) ?>" readonly="readonly"><?php echo $proj->Abstr ?></textarea>
					</div> <?php
					
					# Editors # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resEdtr, $sizeEdtr) = $this->retrieve('edtr', $proj->ID, null, '', ''); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeEdtr)) ? "on" : "off open" ?> next edtr">
						<b>Authors</b> <span><?php echo $sizeEdtr ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($edtr = $resEdtr->fetch_object()) { ?>
									<li>
										<span><?php
											echo $edtr->Lname.", ".$edtr->Fname.' '.substr($edtr->Mname, 0, 1).'.' ?>
										</span>
										<button type="button" class="remove icon read" data-area="edtr" data-id="<?php echo $edtr->ID ?>"></button>
									</li> <?php
								} ?>
							</ol> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="edtr[val][]" class="edtr" type="text" placeholder="Last name, First name, MI" data-guess="acct=guess&edtr=1"/>
								<button class="append icon" type="button" data-area="edtr" data-id="0"></button><br/>
								<input name="edtr[id][]" type="hidden" class="abled">
							</div>
							<div class="edtrs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Sections # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resSec, $sizeSec) = $this->retrieve('sec', $proj->ID, null, '', ''); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeSec)) ? "on" : "off open" ?> next sec">
						<b>Sections</b> <span><?php echo $sizeSec ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { $i = 0;
							while($sec = $resSec->fetch_object()) { ?>
								<span class="sec">
									<textarea name="sec[val][<?php echo $i ?>][head]" readonly="readonly" class="sec head read" rows="<?php echo empty($sec->Header) ? '1' : ceil(strlen($sec->Header)/75) ?>" style="width:633px"><?php echo $sec->Header ?></textarea>
										<button type="button" class="remove icon read right" data-tool="{'head':'Remove section'}" data-area="sec" data-id="<?php echo $sec->CID ?>"></button><br/>
									<textarea name="sec[val][<?php echo $i ?>][cont]" readonly="readonly" rows="<?php echo empty($sec->Content) ? '1' : ceil(strlen($sec->Content)/80) ?>" class="sec cont read"><?php echo $sec->Content ?></textarea>
										<input name="sec[id][<?php echo $i ?>]" type="hidden" value="<?php echo $sec->CID ?>" class="abled"/> <?php
									
									list($resImgSec, $sizeImgSec) = $this->retrieve('sec-img', array($proj->ID, $sec->CID, null, '', 'LIMIT 10'));
									
									if(!empty($sizeImgSec)) {
										while($imgSec = $resImgSec->fetch_object()) { ?>
											<span class="sec-img">
												<a href="main.php?img=view&id=<?php echo $imgSec->ID ?>">
												<img class="stage sec-img file locked ghost" src="<?php echo $imgSec->Thumb ?>" alt="<?php echo $imgSec->Title ?>" style="width:<?php echo (125/$imgSec->Height)*$imgSec->Width ?>px"
													data-id="<?php echo $imgSec->ID ?>" data-src="<?php echo $imgSec->Path ?>" data-visib="<?php echo $imgSec->Visib ?>"
													data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $imgSec->ID ?>\'><?php echo $imgSec->Title ?></a></span>','stay':'true','x':'l'}"/></a>
												<span class="ctrl-img none">
													<span class="ctrl-main">
														<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $imgSec->Thumb ?>" id="pic<?php echo $imgSec->ID ?>"/> <label for="pic<?php echo $imgSec->ID ?>">Default</label>
														<input name="rsecimg[<?php echo $i ?>][]" class="rmv-img abled" type="checkbox" value="<?php echo $imgSec->ID ?>" data-area="micro" id="rsecimg<?php echo $imgSec->ID ?>"/> <label for="rsecimg<?php echo $imgSec->ID ?>">Remove</label>
													</span>
												</span>
											</span> <?php
										} ?> <span class="imgs"></span>
										<a class="fetch img tick" data-area="proj-sec" data-id="<?php echo $sec->CID ?>" data-start="10">Show more</a> <?php
									}
									
									list($resDocSec, $sizeDocSec) = $this->retrieve('sec-doc', array($proj->ID, $sec->CID, null, '', 'LIMIT 10'));
									
									if(!empty($sizeDocSec)) { ?>
										<ol> <?php
											while($docSec = $resDocSec->fetch_object()) { ?>
												<li class="sec-doc">
													<a href="main.php?doc=view&id=<?php echo $docSec->ID ?>"><?php echo $docSec->Title ?></a>
													<button type="button" class="small" data-title="<?php echo $docSec->Title ?>" data-doc="<?php echo $docSec->Path ?>">Open</button>
													<button type="button" class="remove icon read" data-area="secdoc[<?php echo $i ?>]" data-id="<?php echo $docSec->ID ?>"></button><br/>
												</li> <?php
											} ?>
										</ol>
										<a class="fetch doc tick" data-area="proj-sec" data-id="<?php echo $sec->CID ?>" data-start="10">Show more</a> <?php
									}
									else {
										echo "<br/>";
									} ?>
									
									<div class="none">
										<input name="sec[<?php echo $i ?>][]" type="file" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
									</div>
									<button type="button" class="peel on prev read small" data-off="Remove files" data-on="Add files">Add files</button><hr/>
								</span> <?php
								
								$i++;
							}
						} ?>
						
						<div class="none">
							<div class="sec default">
								<input name="asec[val][0][head]" type="text" placeholder="Header" class="sec"/>
								<button type="button" class="append-sec icon" data-area="asec" data-index="0"></button><br/>
								<div class="none">
									<textarea name="asec[val][0][cont]" placeholder="Content" rows="5" class="sec"/></textarea><br/>
									<input name="asec[0][]" type="file" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
								</div>
								<button type="button" class="peel on prev small read block" data-on="Add contents" data-off="Remove contents">Add contents</button>
								<input name="asec[id][0]" type="hidden" class="abled"/>
							</div>
							<div class="secs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($proj->Notes) or $proj->Notes=='NULL')) ? "on" : "off open" ?> next notes"><b>Notes</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="notes" class="notes read" rows="<?php echo empty($proj->Notes) ? '5' : ceil(strlen($proj->Notes)/100) ?>" readonly="readonly"><?php echo $proj->Notes ?></textarea>
					</div>  <?php 
					
					# Microorganisms # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					
					list($resMicro, $sizeMicro) = $this->retrieve('micro', $proj->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeMicro)) ? "on" : "off open" ?> next micro">
						<b>Microorganisms</b> <span><?php echo $sizeMicro ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($micro = $resMicro->fetch_object()) { ?>
									<li>
										<a href="main.php?micro=view&id=<?php echo $micro->ID ?>"><i> <?php
											echo $micro->Name ?></i></a> <span class="dim"><?php echo $micro->Authors ?></span>
										<button type="button" class="remove icon read" data-area="micro" data-id="<?php echo $micro->ID ?>"></button>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch micro" data-area="proj" data-id="<?php echo $proj->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="micro[val][]" type="text" class="micro" placeholder="Scientific name" data-guess="micro=guess"/>
								<button class="append icon" type="button" data-area="micro" data-id="0"></button>
								<input type="hidden" name="micro[id][]" class="abled">
							</div>
							<div class="micros"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php 
					
					# Images # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resImg, $sizeImg) = $this->retrieve('img', $proj->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeImg)) ? "on" : "off open" ?> next img">
						<b>Images</b> <span><?php echo $sizeImg ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { $i = 0;
							while($img = $resImg->fetch_object()) { if($i++==0) $imgPath = $img->Path; ?>
								<span class="img">
									<a href="main.php?img=view&id=<?php echo $img->ID ?>">
									<img class="stage file locked ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
										data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
										data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
									<span class="ctrl-img none">
										<span class="ctrl-main">
											<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
											<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" data-area="proj" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
										</span>
									</span>
								</span> <?php
							} ?> <div class="imgs"></div>
							<a class="fetch img tick" data-area="proj" data-id="<?php echo $proj->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="img[val][]" class="img" type="text" placeholder="Image title" data-guess="img=guess"/>
								<button class="append icon" type="button" data-area="img" data-id="0"></button>
								<input name="img[id][]" type="hidden" class="abled"/>
							</div>
							<div class="imgs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php 
					
					# Documents # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resDoc, $sizeDoc) = $this->retrieve('doc', $proj->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeDoc)) ? "on" : "off open" ?> next doc">
						<b>Documents</b> <span><?php echo $sizeDoc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($doc = $resDoc->fetch_object()) { ?>
									<li class="doc">
										<a href="main.php?doc=view&id=<?php echo $doc->ID ?>" target="_blank" data-title="<?php echo $doc->Title ?>" title="<?php echo $doc->Title ?>"
											data-doc="<?php echo $doc->Path ?>"><?php echo empty($doc->Ref) ? $doc->Title : $doc->Ref ?></a>
										<button type="button" class="remove icon read" data-area="doc" data-id="<?php echo $doc->ID ?>"></button>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch doc tick" data-area="proj" data-id="<?php echo $proj->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="doc" name="doc[val][]" placeholder="Document title" data-guess="doc=guess"/>
								<button class="append icon" type="button" data-area="doc" data-id="0"></button>
								<input type="hidden" name="doc[id][]" class="abled"/>
							</div>
							<div class="docs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php 
					
					# Locations # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resLoc, $sizeLoc) = $this->retrieve('loc', $proj->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeLoc)) ? "on" : "off open" ?> next loc">
						<b>Locations</b> <span><?php echo $sizeLoc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($loc = $resLoc->fetch_object()) { ?>
									<li class="loc">
										<a href="main.php?loc=view&id=<?php echo $loc->ID ?>"><?php echo $loc->Name ?></a>
										<button type="button" class="remove icon read" data-area="loc" data-id="<?php echo $loc->ID ?>"></button>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch loc tick" data-area="proj" data-id="<?php echo $proj->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="loc[val][]" type="text" class="loc" placeholder="Location name" data-guess="loc=guess"/>
								<button class="append icon" type="button" data-area="loc" data-id="0"></button>
								<input type="hidden" name="loc[id][]" class="abled"/>
							</div>
							<div class="locs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Resources # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resRsrc, $sizeRsrc) = $this->retrieve('rsrc', $proj->ID, null, '', 'LIMIT 10'); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeRsrc)) ? "on" : "off open" ?> next rsrc">
						<b>Resources</b> <span><?php echo $sizeRsrc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($rsrc = $resRsrc->fetch_object()) { ?>
									<li class="rsrc">
										<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>"><?php echo $rsrc->Title ?></a>
										<button type="button" class="remove icon read" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>"></button>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch rsrc tick" data-area="proj" data-id="<?php echo $proj->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="rsrc" name="rsrc[val][]" placeholder="Resource title" data-guess="rsrc=guess"/>
								<button class="append icon" type="button" data-area="rsrc" data-id="0"></button>
								<input type="hidden" name="rsrc[id][]" class="abled"/>
							</div>
							<div class="rsrcs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Sources # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
					list($resSrce, $sizeSrce) = $this->retrieve('srce', $proj->ID, null, '', ''); ?>
					
					<div class="div-peel peel on next srce"><b>Sources</b></div>
					<div class="div-case none"> <?php
						if(!empty($sizeSrce)) { ?>
							<ol> <?php
								while($srce = $resSrce->fetch_object()) { ?>
									<li class="srce">
										<input name="srce[journ][]" value="<?php echo $srce->Journ ?>" type="text" class="reqd read skip" readonly="readonly" placeholder="Journal title" data-tool="{'head':'Journal','x':'l'}"/>
											<button type="button" class="remove icon read" data-area="srce" data-id="<?php echo $srce->CID ?>"></button>
										<div style="padding-left:15px">
											<input name="srce[year][]" value="<?php echo $srce->Year ?>" type="text" class="code number abled read skip" readonly="readonly" placeholder="Year" data-tool="{'head':'Year','x':'l'}"/>
											<input name="srce[vol][]" value="<?php echo $srce->Vol ?>" type="text" class="code number abled read skip" readonly="readonly" placeholder="Volume" data-tool="{'head':'Volume','x':'l'}"/>
											<input name="srce[num][]" value="<?php echo $srce->Num ?>" type="text" class="code number abled read skip" readonly="readonly" placeholder="Number" data-tool="{'head':'Number','x':'l'}"/>
											<input name="srce[page][]" value="<?php echo $srce->Page ?>" type="text" class="code number abled read skip" readonly="readonly" placeholder="Page(s)" data-tool="{'head':'Page(s)','x':'l'}"/>
											<input name="srce[id][]" value="<?php echo $srce->CID ?>" type="hidden" class="abled"/>
										</div>
									</li> <?php
								} ?>
							</ol> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="asrce[journ][]" type="text" class="abled skip" placeholder="Journal title" data-tool="{'head':'Journal','x':'l'}"/>
									<button class="append-srce icon" type="button" data-area="srce"></button><br/>
								<div class="none">
									<input name="asrce[year][]" type="text" class="code number abled skip" placeholder="Year" data-tool="{'head':'Year','x':'l'}"/>
									<input name="asrce[vol][]" type="text" class="code number abled skip" placeholder="Volume" data-tool="{'head':'Volume','x':'l'}"/>
									<input name="asrce[num][]" type="text" class="code number abled skip" placeholder="Number" data-tool="{'head':'Number','x':'l'}"/>
									<input name="asrce[page][]" type="text" class="code number abled skip" placeholder="Page(s)" data-tool="{'head':'Page(s)','x':'l'}"/>
								</div>
								<a class="addmore peel on prev" data-on="Add details" data-off="Remove details">Add details</a>
							</div>
							<div class="srces"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php
					
					# Files # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?>
					<div class="div-peel peel on next file none"><b>Files</b></div>
					<div class="div-case none file">
						<input name="file[]" type="file" class="file" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($proj->Ref) or $proj->Ref=='NULL')) ? "on" : "off open" ?> next ref">
						<b>References</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="ref" rows="<?php echo $empty ? '3' : ceil(strlen($proj->Ref)/100) ?>" class="read abled" readonly="readonly"> <?php
							echo $proj->Ref ?></textarea>
					</div>
					
					<div class="div-case pdoc none">
						<label>Primary document:</label><br/>
						<input name="pdoc" type="file" accept="application/pdf"/>
					</div> <?php
					
					# Inputs # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?><div class="div-peel peel on next file none"><b>Update</b></div>
					<div class="div-case file none">
						<input name="input[]" type="file" class="file" accept="application/json"/>
					</div> <?php
					
					# Settings # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ?><div class="div-peel peel on next safe none"><b>Settings</b><span class="setting help"></span></div>
					<div class="div-case none safe"></div>
				</div>
				
				<div class="div-head">
					<img class="default ghost" src="<?php echo empty($proj->ImgPath) ? "template/proj.jpg" : "process.php?img=open&deg=20&path={$proj->ImgPath}" ?>" alt="<?php echo $proj->Title ?>"/>
					
					<div class="controls"> <?php
						if(!empty($proj->DocID)) {
							$doc = new Document(null, null, $this->mysqli, $this->user);
							$docs = $doc->search($proj->DocID, array('c'=>'id'), 0, 1);
							
							if(!empty($docs[1])) {
								$doc = $docs[0]->fetch_object(); ?>
								<button class="open doc dial" type="button" data-title="<?php echo Tool::truncate($doc->Title, 80) ?>" data-doc="<?php echo $doc->Path ?>">Open</button><hr/> <?php
							}
						} ?>
						
						<button class="share dial" data-area="proj" data-id="<?php echo $proj->ID ?>" type="button"><span>Share</span></button> <?php
						
						$sett = new Setting('proj', null, $this->mysqli, $this->user);
						$verified = $sett->verify($proj->ID);
						
						# Basic or verified can be downloaded
						if($proj->Categ=='BSC' or $verified) { ?>
							<a href="process.php?proj=get&id=<?php echo $proj->ID ?>"><span class="dload dial button"><span>Download</span></span></a> <?php
						} ?><hr/>
						
						<button class="details dial" type="button" data-area="proj" data-id="<?php echo $proj->ID ?>" data-name="<?php echo $proj->Title ?>"><span>Details</span></button>
						
						<button class="stat dial peel on next" type="button"><b>Contents</b></button>
						<ul class="metas none">
							<li class="meta">Microorganisms <span><?php echo $sizeMicro ?></span></li>
							<li class="meta">Authors <span><?php echo $sizeEdtr ?></span></li>
							<li class="meta">Sections <span><?php echo $sizeSec ?></span></li>
							<li class="meta">Images <span><?php echo $sizeImg ?></span></li>
							<li class="meta">Documents <span><?php echo $sizeDoc ?></span></li>
							<li class="meta">Locations <span><?php echo $sizeLoc ?></span></li>
							<li class="meta">Resources <span><?php echo $sizeRsrc ?></span></li>
						</ul> <?php
						
						# Author or coeditor or Prime is currently logged in and can edit project
						if($verified) { ?><hr/>
							<button class="edit dial" data-area="proj" data-id="<?php echo $proj->ID ?>" type="reset"><span>Edit</span></button> <?php
						} ?>
					</div>
				</div>
				
				<div class="div-mind">
					<input name="id" type="hidden" class="id abled" value="<?php echo $proj->ID ?>"/>
					<input name="upd" type="checkbox" class="abled" value="<?php echo $proj->ID ?>"/>
					<input name="recov" type="checkbox" class="recov abled" value="<?php echo $proj->ID ?>"/>
					<input name="del" type="checkbox" class="del abled" value="<?php echo $proj->ID ?>"/>
				</div>
			</div>
			
			<div class="div-dial"> <?php
				if($proj->Remove=='0') { ?>
					<button class="delete tick read left" type="button" form="form-proj<?php echo $proj->ID ?>" data-area="proj">Delete</button> <?php
				}
				else { ?>
					<button class="recover tick read left" type="button" form="form-proj<?php echo $proj->ID ?>" data-area="proj">Recover</button> <?php
				} ?>
				<button type="button" form="form-proj<?php echo $proj->ID ?>" class="cancel edit read">Cancel</button>
				<button type="submit" class="read">Update</button> <?php
				
				if(!$cont) { ?>
					<button type="button" class="close-content reset">Close</button> <?php
				} ?>
			</div>
			</form>
		</div> <?php
	}
}
?>